/*
 * Copyright (c) 2025 Li Auto Inc. and its affiliates
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "UDSStreamAcceptor.h"
#include <deps/common/IPLocator.h>
#include "UDSStreamTransportInterface.h"

namespace vbs {
namespace transport {
using IPLocator = vbsutil::xmlparser::IPLocator;

UDSStreamAcceptor::UDSStreamAcceptor(asio::io_service& io_service, UDSStreamTransportInterface* parent,
                                     const Locator& locator)
    : io_service_(&io_service),
      locator_(locator),
      socket_(io_service),
      acceptor_(io_service, asio::local::stream_protocol::endpoint(IPLocator::getPathFromLocator(locator))) {
    (void)parent;
}

UDSStreamAcceptor::UDSStreamAcceptor(asio::io_service& io_service, const std::string& interface, const Locator& locator)
    : io_service_(&io_service),
      locator_(locator),
      socket_(io_service),
      acceptor_(io_service, asio::local::stream_protocol::endpoint(interface)) {
    (void)interface;
}

UDSStreamAcceptor::UDSStreamAcceptor(asio::io_service& io_service, const Locator& locator)
    : io_service_(&io_service),
      locator_(locator),
      socket_(io_service),
      acceptor_(io_service, asio::local::stream_protocol::endpoint(IPLocator::getPathFromLocator(locator))) {}

void UDSStreamAcceptor::accept(UDSStreamTransportInterface* parent) {
    const Locator locator = locator_;
    auto new_socket = std::make_shared<asio::local::stream_protocol::socket>(*io_service_);
    acceptor_.async_accept(*new_socket, [new_socket, parent, locator](const std::error_code& error) {
        if (!error) {
            auto socket = std::make_shared<asio::local::stream_protocol::socket>(std::move(*new_socket));
            parent->SocketAccepted(std::move(socket), locator, error);
        }
    });
}

}  // namespace transport
}  // namespace vbs
